package com.jvm123.minio.service.temp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 *
 * @author yawn http://jvm123.com
 * 2020/1/18 10:59
 */
public class DefaultTempCleanService implements TempCleanService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTempCleanService.class);

    @Override
    public void cleanTemp(String tmpDir, Long tmpAliveDuration) {

        if (tmpAliveDuration == null || tmpAliveDuration <= 0) {
            LOGGER.warn("Temp dir is not cleared, due to temp files alive duration: {}", tmpAliveDuration);
            return;
        }
        LOGGER.info("Clean temp dir {}, duration: {}", tmpDir, tmpAliveDuration);
        File dir = new File(tmpDir);
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files == null) {
                return;
            }
            long currentTime = System.currentTimeMillis();
            for (File file : files) {
                long lastModified = file.lastModified();
                if (file.canWrite() && (currentTime - lastModified >= tmpAliveDuration)) {
                    file.delete();
                }
            }
        }
    }

}
